//
//  YXTopicViewController.m
//  CreditCard
//
//  Created by 杨旭 on 2017/12/27.
//  Copyright © 2017年 杨旭. All rights reserved.
//

#import "YXTopicViewController.h"
#import "YXTopicToolbarView.h"
#import "YXReplyLandlordView.h"
#import "YXTopicModel.h"
#import "YXReplyModel.h"
#import "YXPostModel.h"
#import "YXReplyCell.h"
#import "YXTopicCell.h"
#import "YXTopicHeaderView.h"
#import "YXReplyTableView.h"
#import "YXReplyHeaderView.h"
@interface YXTopicViewController ()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,strong) UIView *playView;
@property (nonatomic ,strong) YXTopicHeaderView *topicHeaderView;
@property (nonatomic ,strong) YXReplyTableView *tableView;
@property (nonatomic, strong) NSNumber *duration;
@property (nonatomic, strong) NSNumber *curve;
@property (nonatomic, assign) CGFloat replyLandlordViewY;
@property (nonatomic ,strong) YXTopicToolbarView *toolbarView;
@property (nonatomic ,strong) YXReplyLandlordView *replyLandlordView;
@property (nonatomic ,strong) YXTopicModel *model;
@property (nonatomic ,strong) YXPostModel *postModel;
@property (nonatomic ,strong) NSMutableArray *replyListArr;
@end

@implementation YXTopicViewController


- (NSMutableArray *)replyListArr {
    if (!_replyListArr) {
        _replyListArr = [NSMutableArray array];
    }
    return _replyListArr;
}

- (UIView *)playView {
    if (!_playView) {
        _playView = [[UIView alloc] initWithFrame:(CGRectMake(0, 0, kScreenWidth, 200))];
        _playView.backgroundColor = [UIColor blackColor];
    }
    return _playView;
}

- (YXTopicHeaderView *)topicHeaderView {
    if (!_topicHeaderView) {
        _topicHeaderView = [[YXTopicHeaderView alloc] initWithFrame:(CGRectMake(0, 0, kScreenWidth, 120))];
    }
    return _topicHeaderView;
}

- (YXReplyTableView *)tableView {
    if (!_tableView) {
        _tableView = [[YXReplyTableView alloc] initWithFrame:(CGRectMake(0, 0, kScreenWidth, kScreenHeight-50-64)) style:(UITableViewStylePlain)];
        _tableView.delegate = self;
        _tableView.dataSource = self;

        _tableView.tableHeaderView = self.topicHeaderView;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
        [_tableView addGestureRecognizer:tap];

        [_tableView registerNib:[UINib nibWithNibName:@"YXTopicCell" bundle:nil] forCellReuseIdentifier:@"YXTopicCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"YXReplyCell" bundle:nil] forCellReuseIdentifier:@"YXReplyCell"];

    }
    return _tableView;
}
- (void)tapAction {
    [self.toolbarView.contentTF resignFirstResponder];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self createLeftBarButtonItemWithImage:@"导航栏_002"];
    self.title = @"话题";
    [self createNarBarUI];
    [self requestData];

}
- (void)createNarBarUI {
    UIBarButtonItem *shareBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"导航栏_001"] style:(UIBarButtonItemStyleDone) target:self action:@selector(shareBtnAction)];
    self.navigationItem.rightBarButtonItem = shareBtn;
}
- (void)shareBtnAction {
    
}
- (void)requestData {
//http://121.196.210.134:8082/mpos/wx/selectPost.do?sessionId=c517b5c1-4352-4c20-a336-5fb4ad31a24f&id=1
    NSString *urlStr = @"selectPost.do";
    NSDictionary *parameter = @{@"sessionId":[YXUserInfoManager getUserInfo].sessionId,@"id":self.ID};
    [BX_NetWorkManager requestForPOSTWithUrl:urlStr parameter:parameter success:^(id responseObject) {
        NSLog(@"%@",responseObject);
        if (REQUESTDATASUCCESS) {
            self.model = [YXTopicModel mj_objectWithKeyValues:responseObject[@"body"]];
            self.postModel = [YXPostModel mj_objectWithKeyValues:responseObject[@"body"][@"post"]];
            
            self.replyListArr = [YXReplyModel mj_objectArrayWithKeyValuesArray:responseObject[@"body"][@"postReplyList"]];
            // 根据帖子类型展示界面
            if ([self.postModel.type isEqualToString:@"0"]) {  // 图文
                [self topicHeaderView];
                self.tableView.replyListArr = self.replyListArr;
                self.topicHeaderView.model = self.model;
                self.topicHeaderView.postModel = self.postModel;
                [self.view addSubview:self.tableView];

                
            }else if ([self.postModel.type isEqualToString:@"1"]) { // 视频
             
                self.tableView.contentInset = UIEdgeInsetsMake(200, 0, 50, 0);
                [self topicHeaderView];
                self.tableView.replyListArr = self.replyListArr;
                self.topicHeaderView.model = self.model;
                self.topicHeaderView.postModel = self.postModel;
                [self.view addSubview:self.tableView];
                [self.view addSubview:self.playView];

                
                
            }else {  // 文字
                
            }
      
            [self createToolBarUI];
            [self.tableView reloadData];
        }
    } failure:^(NSError *error) {
        [self showAlertWithTitle:@"提示" Messge:@"维护中，请稍等！"];
    }];
    
}

- (void)requestDataReplyPostLevel:(NSString *)level RepliesID:(NSString *)repliesID PostID:(NSString *)postID {
    //    http://121.196.210.134:8082/mpos/wx/replyPost.do?sessionId=sdder3453dhj&contents=留言回复&level=1&replies_agent_id=1&post_reply_id2
    NSString *urlStr = @"replyPost.do";
    NSDictionary *parameter = @{@"sessionId":[YXUserInfoManager getUserInfo].sessionId,@"contents":self.toolbarView.contentTF.text,@"level":level,@"replies_agent_id":repliesID,@"post_reply_id":postID};
    [BX_NetWorkManager requestForPOSTWithUrl:urlStr parameter:parameter success:^(id responseObject) {
        NSLog(@"请求成功%@",responseObject);
        [self requestData];
        [self.toolbarView.contentTF resignFirstResponder];
        [self showTostMessage:@"评论成功！"];
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
    
}


- (void)createToolBarUI {
    _toolbarView = [[YXTopicToolbarView alloc] initWithFrame:(CGRectMake(0, kScreenHeight - 50 - 64, kScreenWidth, 50))];
    _toolbarView.contentTF.delegate = self;
    _toolbarView.contentTF.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:self.toolbarView];
    YXWeakSelf
    [_toolbarView setClickSendBtnBlick:^{
        
        if (_toolbarView.contentTF.text.length == 0) {
            [weakSelf showTostMessage:@"评论不能为空！"];
            [weakSelf.toolbarView.contentTF resignFirstResponder];

        }else {
            [weakSelf requestDataReplyPostLevel:@"1" RepliesID:@"1" PostID:weakSelf.postModel.ID];
        }

    }];
    
    
    // 通知-监听键盘弹出事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeKeyboardWillShowNotification:) name:UIKeyboardWillShowNotification object:nil];
    // 通知-监听键盘回收事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeKeyboardWillHideNotification:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)changeKeyboardWillShowNotification:(NSNotification *)notification
{
    NSDictionary *userInfo = [notification userInfo];
    // 键盘弹出后的frame的结构体对象
    NSValue *valueEndFrame = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    // 得到键盘弹出后的键盘视图所在y坐标
    CGFloat keyBoardEndY = valueEndFrame.CGRectValue.origin.y-64;
    // 键盘弹出的动画时间
    self.duration = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    // 键盘弹出的动画曲线
    self.curve = [userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    // 添加移动动画，使视图跟随键盘移动(动画时间和曲线都保持一致)
    [UIView animateWithDuration:[_duration doubleValue] animations:^{
        [UIView setAnimationBeginsFromCurrentState:YES];
        // 不设置这个,大家可以看看有什么区别
        [UIView setAnimationCurve:[_curve intValue]];
        _toolbarView.center = CGPointMake(_toolbarView.center.x, keyBoardEndY - _toolbarView.bounds.size.height/2.0);
        
        if (iPhone6Plus_6sPlus) {
            _replyLandlordViewY = (keyBoardEndY - _toolbarView.bounds.size.height/2.0)-5.0;
        }else {
            _replyLandlordViewY = (keyBoardEndY - _toolbarView.bounds.size.height/2.0)+ 38;
        }
        _replyLandlordView.frame = CGRectMake(0, kScreenHeight - _replyLandlordViewY-64, kScreenWidth, 50);
        
    }];
    /**
     *  + (void)setAnimationCurve:(UIViewAnimationCurve)curve;
     *  typedef NS_ENUM(NSInteger, UIViewAnimationCurve) {
     *  UIViewAnimationCurveEaseInOut,         // 淡入淡出，开始时慢，由慢变快，中间最快，然后变慢
     *  UIViewAnimationCurveEaseIn,            // 淡入，开始时慢然后越来越快
     *  UIViewAnimationCurveEaseOut,           // 淡出，开始快然后越来越慢
     *  UIViewAnimationCurveLinear             // 线性匀速，开始和结束是一个速度
     *  };
     */
}

- (void)changeKeyboardWillHideNotification:(NSNotification *)notification
{
    NSDictionary *userInfo = [notification userInfo];
    // 键盘弹出前的frame的结构体对象
    NSValue *valueStatrFrame = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    // 得到键盘弹出后的键盘视图所在y坐标
    CGFloat keyBoardStatrY = valueStatrFrame.CGRectValue.origin.y-64;
    
    [UIView animateWithDuration:[_duration doubleValue] animations:^{
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationCurve:[_curve intValue]];
        _toolbarView.center = CGPointMake(_toolbarView.center.x, keyBoardStatrY - _toolbarView.bounds.size.height/2.0);
    }];
}

#pragma mark - ScrollView Delegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - TextField Delegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {

    [UIView animateWithDuration:0.1 animations:^{
        _replyLandlordView = [[YXReplyLandlordView alloc] initWithFrame:(CGRectMake(0, kScreenHeight , kScreenWidth, 50))];
        _replyLandlordView.model = self.postModel;
        _toolbarView.contentTF.placeholder = [NSString stringWithFormat:@"回复   %@",_postModel.nickname];
        [self.view addSubview:self.replyLandlordView];
    }];
    return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
    _toolbarView.contentTF.placeholder = [NSString stringWithFormat:@"写回复"];
    [self.replyLandlordView removeFromSuperview];
}


#pragma mark - UITableView Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.replyListArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [[UITableViewCell alloc] init];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    YXReplyHeaderView *headerView = [[YXReplyHeaderView alloc] initWithFrame:(CGRectMake(0, 0, kScreenWidth, 120))];
    headerView.model = self.replyListArr[section];
    
//    YXWeakSelf
//    [headerView setClickContent:^(YXReplyModel *model) {
//        NSLog(@"%@",model.repliesAgentId);
//        NSString *urlStr = @"replyPost.do";
//        NSDictionary *parameter = @{@"sessionId":[YXUserInfoManager getUserInfo].sessionId,@"contents":@"why",@"level":@"2",@"replies_agent_id":model.repliesAgentId,@"post_reply_id":model.postReplyId};
//        [BX_NetWorkManager requestForPOSTWithUrl:urlStr parameter:parameter success:^(id responseObject) {
//            NSLog(@"请求成功%@",responseObject);
//            [self requestData];
//            [self.toolbarView.contentTF resignFirstResponder];
//            [self showTostMessage:@"评论成功！"];
//        } failure:^(NSError *error) {
//            NSLog(@"%@",error);
//
//        }];
    
//        [weakSelf requestDataReplyPostLevel:@"2" RepliesID:model.repliesAgentId PostID:@"1"];
        
//    }];
    return headerView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    YXReplyModel *model = [self.replyListArr objectAtIndex:section];
    CGFloat contentHeight = [self getHeightWtih:model.contents WithFont:14];
    return contentHeight + 90;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *backView = [[UIView alloc] initWithFrame:(CGRectMake(0, 0, kScreenWidth,10))];
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = color_lineColor;
    [backView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.and.right.equalTo(backView);
        make.height.mas_equalTo(1);
    }];
    return backView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    YXReplyModel *model = [self.replyListArr objectAtIndex:section];
    return model.replyAgentContents == nil  ? 1 : 10;
}


#pragma maek - 根据cell上字符串的长度和label的字体大小，计算label的高度
- (CGFloat)getHeightWtih:(NSString *)contentStr WithFont:(CGFloat)font {
    CGSize size = [contentStr boundingRectWithSize:(CGSizeMake(kScreenWidth - 20, MAXFLOAT)) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:font]} context:nil].size;
    if (contentStr.length > 0) {
        return size.height - 17;
    }
    return size.height;
    
}
@end
